package updateDatabases;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * Gets the IGN score from the web
 * @author Matthew Mizumoto
 *
 */

public class IgnScore {
  static String ign;

  public static String Ign(String name) {
    ArrayList<String> sourceLines = new ArrayList<String>();
    String source = "";
    try {
      sourceLines = urlToArrayList(setSearchPhraseIgn(name));
      for (String str : sourceLines) {

        source += (str);
      }
      ign = setIgnScore(source);

    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return ign;
  }

  public static void main(String[] args) {
    ArrayList<String> sourceLines = new ArrayList<String>();
    String searchPhrase = "Call of Duty: Modern Warfare 3 ";
    String source = "";
    try {
      sourceLines = urlToArrayList(setSearchPhraseIgn(searchPhrase));
      for (String str : sourceLines) {
        source += (str);
      }
      System.out.println(setIgnScore(source));
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 
   * @param url The URL to retrieve source code from.
   * @return sourceCode The source code from the URL.
   * @throws IOException
   */
  public static ArrayList<String> urlToArrayList(String url) throws IOException {
    Scanner openFile;
    int counter = 0;
    ArrayList<String> sourceCode = new ArrayList<String>();
    URL passedURL = new URL(url);
    openFile = new Scanner(passedURL.openStream());
    while (openFile.hasNext()) {
      sourceCode.add(openFile.nextLine());
      counter++;
    }
    return sourceCode;
  }

  /**
   * Sets search phrase to send to metacritic
   * 
   * @param searchPhrase The game to search
   * @return address The address to query metacritic
   */
  public static String setSearchPhraseIgn(String searchPhrase) {
    searchPhrase = searchPhrase.trim();
    searchPhrase = searchPhrase.replaceAll(" ", "+");
    String address = "http://www.ign.com/search/product?query=";
    address = address.concat(searchPhrase);
    return address;
  }

  /**
   * Gets the meta score from the ign source code.
   * 
   * @param source The source code to parse.
   * @return
   */
  public static String setIgnScore(String source) {
    source = source.replaceFirst("<.*<div id=\"searchResults\">", "<div id=\"searchResults\">");
    source = source.replaceFirst("<.*?<span class=\"ratingBox\">", "<span class=\"ratingBox\">");
    source = source.replaceFirst("<", "");
    source = source.replaceFirst("<.*", "");
    source = source.replaceFirst(".*>", "");
    source = source.trim();
    String ign = source;
    return ign;
  }
}
